package cn.ydxiaoshuai.modules.weixin.util;

import cn.hutool.http.HttpUtil;
import cn.ydxiaoshuai.common.api.vo.weixin.WeiXinConts;
import cn.ydxiaoshuai.common.util.RedisUtil;
import cn.ydxiaoshuai.common.util.oConvertUtils;
import cn.ydxiaoshuai.modules.weixin.entity.WeixinAccount;
import cn.ydxiaoshuai.modules.weixin.po.*;
import cn.ydxiaoshuai.modules.weixin.service.IWeixinAccountService;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Formatter;
import java.util.UUID;

/**
 * @author 小帅丶
 * @Description 微信工具类
 * @className WXTemplatUtil
 * @Date 2019/11/28-9:51
 **/
@Component
public class WXUtil {
    @Autowired
    private RedisUtil redisUtil;
    @Autowired
    private IWeixinAccountService weixinAccountService;

    /**
     * @Description 发送模板消息
     * @Author 小帅丶
     * @Date  2019/11/28 9:58
     * @param tempMsg 模板消息对象
     * @return java.lang.String
     **/
    public String sendTempMsg(WxTemplate tempMsg) {
        String access_token = redisUtil.get("access_token").toString();
        String apiUrl = WXAPI.TEMPLATE_SEND_URL.replace("ACCESS_TOKEN", access_token);
        String param = JSON.toJSONString(tempMsg);
        String result = HttpUtil.post(apiUrl, param);
        return result;
    }
    /**
     * @Description 获取AccessToken
     * @Author 小帅丶
     * @Date  2020年9月10日17:35:10
     * @param weixinAccount 微信账号对象
     * @return java.lang.String
     **/
    public String getAccessToken(WeixinAccount weixinAccount) {
        String access_token = "";
        WXAccessToken wxAccessToken = getAccessTokenByBean(weixinAccount);
        if(oConvertUtils.isEmpty(wxAccessToken.getErrcode())){
            access_token = wxAccessToken.getAccess_token();
        } else {
            access_token = null;
        }
        return access_token;
    }
    /**
     * @Description 获取AccessToken
     * @Author 小帅丶
     * @Date  2020年9月10日17:33:49
     * @param weixinAccount 微信账号对象
     * @return java.lang.String
     **/
    public WXAccessToken getAccessTokenByBean(WeixinAccount weixinAccount) {
        String apiUrl = WXAPI.GET_TOKEN_URL.replace("APPID", weixinAccount.getAccountAppid()).replace("APPSECRET", weixinAccount.getAccountAppsecret());
        String result = HttpUtil.get(apiUrl);
        WXAccessToken wxAccessToken = JSONObject.parseObject(result, WXAccessToken.class);
        return wxAccessToken;
    }
    /**
     * @Description 获取AccessToken
     * @Author 小帅丶
     * @Date  2019/11/28 9:58
     * @param appid 微信APPID
     * @param appsecret 微信APPSECRET
     * @return java.lang.String
     **/
    public String getAccessToken(String appid,String appsecret) {
        String apiUrl = WXAPI.GET_TOKEN_URL.replace("APPID", appid).replace("APPSECRET", appsecret);
        String result = HttpUtil.get(apiUrl);
        return result;
    }
    /**
     * @Description 获取AccessToken
     * @Author 小帅丶
     * @Date  2019/11/28 9:58
     * @param appid 微信APPID
     * @param appsecret 微信APPSECRET
     * @return JSONObject
     **/
    public JSONObject getAccessTokenByJSON(String appid, String appsecret) {
        String apiUrl = WXAPI.GET_TOKEN_URL.replace("APPID", appid).replace("APPSECRET", appsecret);
        String result = HttpUtil.get(apiUrl);
        return JSONObject.parseObject(result);
    }
    /**
     * @Description 获取JSAPITicket
     * @Author 小帅丶
     * @Date  2019/11/28 9:58
     * @param accessToken 微信accessToken
     * @return WXJSAPITicket
     **/
    public WXJSAPITicket getJSTicket(String accessToken) {
        String apiUrl = WXAPI.GET_TICKET_URL.replace("ACCESS_TOKEN", accessToken);
        String result = HttpUtil.get(apiUrl);
        WXJSAPITicket wxjsapiTicket = JSONObject.parseObject(result, WXJSAPITicket.class);
        return wxjsapiTicket;
    }


    /**
     * @Description 根据小程序授权code获取AccessToken
     * @Author 小帅丶
     * @Date  2020年4月2日10:37:46
     * @param code 网页授权返回的code
     * @param account_code 小程序的内部编码
     * @return String
     **/
    public String getAccessTokenByCodeAppid(String code,String account_code) {
//        WeiXinConts weiXinConts = null;
//        if(redisUtil.hasKey(account_code)){
//            weiXinConts = (WeiXinConts)redisUtil.get(account_code);
//        } else {
//            weixinAccountService.refreshOneAppid(account_code);
//            weiXinConts = (WeiXinConts)redisUtil.get(account_code);
//        }
        String url = WXAPI.JSCODE2SESSION_URL.replace("APPID", "wx83b10d1a7b8d2310").
                replace("SECRET","8f9dcf7dec99de8267ef37749638c026").replace("JSCODE", code);
        String result = HttpUtil.get(url);
        return result;
    }

    /**
     * @Description 根据网页授权code获取openid  获取用户信息
     * @Author 小帅丶
     * @Date  2019/12/03
     * @param openid 微信用户唯一编码
     * @return String
     **/
    public String getWXUserInfoDetail(String openid) {
        String access_token = redisUtil.get("access_token").toString();
        String url = WXAPI.GET_USERINFO_NO_OAUTH_URL.replace("ACCESS_TOKEN", access_token).replace("OPENID", openid);
        String result = HttpUtil.get(url);
        return result;
    }
    /**
     * @Description 根据网页授权code获取openid  获取用户信息
     * @Author 小帅丶
     * @Date  2019/12/03
     * @param openid 微信用户唯一编码
     * @return WXUserInfoDetail
     **/
    public WXUserInfoDetail getWXUserInfoDetailByBean(String openid) {
        String result = getWXUserInfoDetail(openid);
        WXUserInfoDetail userInfo = JSONObject.parseObject(result, WXUserInfoDetail.class);
        return userInfo;
    }
    /**
     * @Description 根据网页授权code获取AccessToken 和 openid 获取用户信息
     * @Author 小帅丶
     * @Date  2019/12/03
     * @param access_token 网页授权返回的code 获取的AccessToken
     * @param openid 微信用户唯一编码
     * @return String
     **/
    public String getWXUserInfo(String access_token, String openid) {
        String url = WXAPI.GET_USERINFO_URL.replace("ACCESS_TOKEN", access_token).replace("OPENID", openid);
        String result = HttpUtil.get(url);
        return result;
    }
    /**
     * @Description 根据网页授权code获取AccessToken 和 openid 获取用户信息
     * @Author 小帅丶
     * @Date  2019/12/03
     * @param access_token 网页授权返回的code 获取的AccessToken
     * @param openid 微信用户唯一编码
     * @return String
     **/
    public WXUserInfo getWXUserInfoByBean(String access_token, String openid) {
        String result = getWXUserInfo(access_token,openid);
        WXUserInfo userInfo = JSONObject.parseObject(result, WXUserInfo.class);
        return userInfo;
    }
    /**
     * @description 获取JSAPI
     * @Author 小帅丶
     * @Date  2019/12/2 14:00
     * @param url 当前请求的地址
     * @return JSAPIPageBean
     **/
    public JSAPIPageBean getJSAPISignBean(String url,String wx_appid){
        JSAPIPageBean bean = new JSAPIPageBean();
        String jsapi_ticket = redisUtil.get("jsapi_ticket").toString();
        String nonce_str = create_nonce_str();
        String timestamp = create_timestamp();
        String string1;
        //签名值
        String signature = "";
        // 注意这里参数名必须全部小写，且必须有序 参数固定就固定写了
        string1 = "jsapi_ticket=" + jsapi_ticket + "&noncestr=" + nonce_str
                + "&timestamp=" + timestamp + "&url=" + url;
        try {
            MessageDigest crypt = MessageDigest.getInstance("SHA-1");
            crypt.reset();
            crypt.update(string1.getBytes("UTF-8"));
            signature = byteToHex(crypt.digest());
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        bean.setAppId(wx_appid);
        bean.setUrl(url);
        bean.setJsapi_ticket(jsapi_ticket);
        bean.setTimestamp(timestamp);
        bean.setNonceStr(nonce_str);
        bean.setSignature(signature);
        return bean;
    }
    /**
     * @Description byte转16进制字符
     * @Author 小帅丶
     * @Date  2019/12/2 14:41
     * @param hash 要转换的byte
     * @return java.lang.String
     **/
    private static String byteToHex(final byte[] hash) {
        Formatter formatter = new Formatter();
        for (byte b : hash)
        {
            formatter.format("%02x", b);
        }
        String result = formatter.toString();
        formatter.close();
        return result;
    }
    /**
     * @Description 随机字符串
     * @Author 小帅丶
     * @Date  2019/12/2 14:42
     * @return java.lang.String
     **/
    private static String create_nonce_str() {
        return UUID.randomUUID().toString();
    }
    /**
     * @Description 时间戳截止到秒
     * @Author 小帅丶
     * @Date  2019/12/2 14:43
     * @return java.lang.String
     **/
    private static String create_timestamp() {
        return Long.toString(System.currentTimeMillis() / 1000);
    }
}
